<?php
namespace file\alioss;

use OSS\OssClient;
use OSS\Core\OssException;

class Alioss
{
    // 阿里云OSS配置
    protected $config = [
        'access_key_id'     => '',
        'access_key_secret' => '',
        'endpoint'          => '',
        'bucket'            => ''
    ];

    /**
     * 需要传入阿里云OSS所需配置
     * Alioss constructor.
     * @param $config
     */
    public function __construct($config)
    {
        // 初始化配置
        foreach ($this->config as $key => $val) {
            $this->config[$key] = $config[$key] ?? "";
        }
    }

    /**
     * 阿里云OSS文件上传
     * @param string $filePath 本地路径
     * @param string $ext 文件后缀
     * @param string $path 路径
     * @return array
     */
    public function uploadFile($filePath, $ext, $path)
    {
        $accessKeyId = $this->config['access_key_id'];
        $accessKeySecret = $this->config['access_key_secret'];
        $endpoint = $this->config['endpoint'];
        $bucket = $this->config['bucket'];
        // 定义文件名称
        $object = $path."/".date("Ymd")."/".time().rand(10000,99999).".".$ext;
        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->uploadFile($bucket, $object, $filePath);
        } catch(OssException $e) {
            return ['status' => false, 'msg' => $e->getMessage()];
        }

        return ['status' => true, 'href' => $object];
    }

    /**
     * 删除文件/多个文件 传入文件路径数组形式
     * $objects = [];
     * $objects[] = "文件名称";
     * $objects[] = "文件名称";
     * @param $objects
     * @return bool
     */
    public function deleteFile($objects)
    {
        $accessKeyId = $this->config['access_key_id'];
        $accessKeySecret = $this->config['access_key_secret'];
        $endpoint = $this->config['endpoint'];
        $bucket = $this->config['bucket'];
        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->deleteObjects($bucket, $objects);
        } catch(OssException $e) {
            return false;
        }

        return true;
    }

}